let v = new Vue({
    el : '#app',
    data: function (){
        return {
            currentUserName: localStorage.getItem('currentUserName'),
            currentUserAvatar: localStorage.getItem('currentUserAvatar'),
            multipleSelection:[],
            /*==========================首页信息模块return结束===========================================*/
            selectedDoctorIndex: "1", //选中的菜单项的index值
            isDoctorCollapse: false,
            defaultDectorOpeneds: ["1"], // 默认展开的菜单项
            selectedDoctorIndex: "1", //选中的菜单项的index值
            /*==========================首页信息模块return结束===========================================*/


            /*==========================医生信息模块return结束===========================================*/
            searchNo: '',//查询输入框的工号
            searchName: '',//查询输入框的username
            isCollapse: false,
            defaultOpeneds: ["1"], // 默认展开的菜单项
            selectedIndex: "1", //选中的菜单项的index值
            multipleSelection: [],//index=2,储存选择的条数
            tableDoctorData: [],
            tableDoctorMhData: [],
            searchData: [],//储存查询结果的数组
            total: 0,//总条数
            pageSize: 5,//每页5条
            currentPage: 1,//
            ids: [],
            departments: [], // 存储科室数据
            dialogDoctorVisible: false, // 控制增加模态框的可见性
            newDoctor: { // 包含新医生的数据
                no: '',
                username: '',
                password: '',
                gender: '',
                deptname: '',
                birthday: '',
                phone: '',
                email: '',
                degree: '',
                joinTime: '',
                deptId: ''
            },
            editedDoctor: {}, // 正在编辑的医生对象
            editModalVisible: false, // 编辑模态框的显示状态
            // 表单规则
            addDoctorRules: {
                no: [
                    {required: true, message: '请输入医生工号', trigger: 'blur'},
                    {pattern: /^D\d{4}$/, message: '工号必须D开头并且是5个长度的字符组成', trigger: 'blur'}
                ],
                username:[
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/, message: '用户名必须是2~10长度的字符组成，且不允许使用标点符号', trigger: 'blur'}
                ],
                gender:[
                    {required: true, message: '性别不能为空', trigger: 'blur'}
                ],
                phone:[
                    {required: true, message: '手机号不能为空', trigger: 'blur'},
                    {pattern:/^1[3456789]\d{9}$/, message: '请输入正确的手机号码'}
                ],
                email:[
                    {required: true, message: '请输入邮箱', trigger: 'blur'},
                    {pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式错误', trigger: 'blur'}
                ],
                deptId:[
                    {required: true, message: '科室不能为空', trigger: 'blur'},
                ],
                birthday:[
                    {required: true, message: '出生日期不能为空', trigger: 'blur'},
                ],
                joinTime:[
                    {required: true, message: '入职时间不能为空', trigger: 'blur'},
                ]
            },
            editDoctorRules:{
                no: [
                    {required: true, message: '请输入医生工号', trigger: 'blur'},
                    {pattern: /^D\d{4}$/, message: '工号必须D开头并且是5个长度的字符组成', trigger: 'blur'}
                ],
                username:[
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {pattern: /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/, message: '用户名必须是2~10长度的字符组成，且不允许使用标点符号', trigger: 'blur'}
                ],
                gender:[
                    {required: true, message: '性别不能为空', trigger: 'blur'}
                ],
                phone:[
                    {required: true, message: '手机号不能为空', trigger: 'blur'},
                    {pattern:/^1[3456789]\d{9}$/, message: '请输入正确的手机号码'}
                ],
                email:[
                    {required: true, message: '请输入邮箱', trigger: 'blur'},
                    {pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式错误', trigger: 'blur'}
                ],
                deptId:[
                    {required: true, message: '科室不能为空', trigger: 'blur'},
                ],
                birthday:[
                    {required: true, message: '出生日期不能为空', trigger: 'blur'},
                ],
                joinTime:[
                    {required: true, message: '入职时间不能为空', trigger: 'blur'},
                ]
            },
            rules: {},


            /*==========================医生信息模块return结束===========================================*/


            /*=========================科室信息模块return开始========================================*/
            tableDeptData: [],
            searchDeptName: '',//绑定查询输入框里面的值
            totalDept: 0,//总条数
            pageSizeDept: 5,//每页5条
            currentPageDept: 1,//
            totalDeptAndDoctor: 0,//总条数
            pageSizeDeptAndDoctor: 5,//每页5条
            currentPageDeptAndDoctor: 1,//
            totalDeptAndDoctorAppoint: 0,//总条数
            pageSizeDeptAndDoctorAppoint: 5,//每页5条
            currentPageDeptAndDoctorAppoint: 1,//
            editModalDeptVisible: false,
            editModalAppointVisible: false,
            newDept:{
                deptremark: ''
            },
            newAppoint:{
                schedulTime: '',
                sourceTotal: '',
                sourceSurplus: '',
                doctorNo: '',
            },
            editedDept: {},
            editedAppoint:{},
            editDeptRules:{
                deptremark:[
                    {required: true, message: '请输入科室备注', trigger: 'blur'},
                    {pattern: /^.{1,20}$/, message: "科室备注必须是1~20长度的字符组成'", trigger: 'blur'}
                ]
            },
            editAppointRules: {
                schedulTime: [
                    {required: true, message: '请输入排班日期', trigger: 'blur'},
                ],
                sourceTotal: [
                    {required: true, message: '请输入号源总量', trigger: 'blur'},
                ],
                sourceSurplus: [
                    {required: true, message: '请输入剩余号源', trigger: 'blur'},
                ]
            },
            showDoctorCard:false,
            showDeptCard:false,
            ListDoctor:[],
            currentDoctorId: -1, // 初始值为一个不存在的科室ID
            tableAppointData:[],//每天排班列表
            showAppointCard:false,
            currentDoctorName: '', // 当前医生的姓名
            currentDoctorNo: '',//当前医生的工号
            loading: false,
            showEmpty:true,
            no: '',
            nickName: '',
            deptId: '',
            searchDeptAppointDate: '',
            doctor:{
                currentDoctorName: '', // 当前医生的姓名
            },
            appointIds:[],
            newAppointRules:{
                schedulTime: [
                    {required: true, message: '请输入排班日期', trigger: 'blur'},
                ],
                sourceTotal: [
                    {required: true, message: '请输入号源总量', trigger: 'blur'},
                ],
                sourceSurplus: [
                    {required: true, message: '请输入剩余号源', trigger: 'blur'},
                ]
            },
            dialogAppointVisible: false,
            showSourceCard: false,
            showSource: false,
            AppointId: '',
            currentAppointId: -1, // 初始值为一个不存在的排班ID
            loadingSource: false,
            ListSource:[],
            newSource:{
                endTime: '',
                sourceSurplus: '',
                sourceTotal: '',
                schedulTime: '',
                appointId: ''
            },
            dialogSourceVisible: false,
            newSourceRules:{
                sourceTotal: [
                    {required: true, message: '请输入号源总量', trigger: 'blur'},
                ],
                sourceSurplus: [
                    {required: true, message: '请输入剩余号源', trigger: 'blur'},
                ]
            },
            AppointTotal: '',//当天排班的号源总量
            AppointSurplus: '',
            sourceTotal: 0,//从数据库累加的号源总量
            sourceSurplus: '',
            AppointStatus: '',
            /*=========================科室信息模块return结束========================================*/



            /*==========================药品信息模块return结束===========================================*/
            tableDrugData: [],//存储预约数据
            totalDrug: 0,//总条数
            pageSizeDrug: 5,//每页5条
            currentPageDrug: 1,//
            drugName:"",
            drugNo:"",



            /*==========================药品信息模块return结束===========================================*/




            /*==========================预约管理模块return结束===========================================*/
            tableBookingData: [],//存储预约数据
            totalBooking: 0,//总条数
            pageSizeBooking: 5,//每页5条
            currentPageBooking: 1,//
            bookDoctorName:"",
            nickName:"",
            bookingIds:"",//批量删除的id
            dialogBookingVisible: false,//新增模态框关闭状态
            newBooking: {
                schedulTime: '',
                healthStatus: ''
            },
            bookingRules:{
                schedulTime:[
                    {required: true, message: '请输入日期', trigger: 'blur'},
                ],
                healthStatus:[
                    {required: true, message: '请输入健康症状', trigger: 'blur'},
                ]
            },
            editedBooking: {},
            editModalBookingVisible: false,
            editBookingRules:{
                schedulTime:[
                    {required: true, message: '请输入日期', trigger: 'blur'},
                ],
                healthStatus:[
                    {required: true, message: '请输入健康症状', trigger: 'blur'},
                ]
            },
            doctorNo:"",
            /*==========================预约管理模块return结束===========================================*/
            /*==========================就诊记录模块return开始===========================================*/
            tableRecordData:[],
            totalRecord: 0,//总条数
            pageSizeRecord: 5,//每页5条
            currentPageRecord: 1,//
            RnickName:"",
            /*==========================就诊记录模块return结束===========================================*/
            /*==========================处方信息模块return开始===========================================*/
            editModalRecordVisible: false,
            editedRecord: {},
            editRecordRules:{
                schedulTime:[
                    {required: true, message: '请输入日期', trigger: 'blur'},
                ],
                announcements:[
                    {required: true, message: '请输入注意事项', trigger: 'blur'},
                ]
            },
            tableRecipeData:[],
            totalRecipe: 0,//总条数
            pageSizeRecipe: 5,//每页5条
            currentPageRecipe: 1,//
            showRecipeCard:false,
            RecipeIds:"",
            dialogVisiblePay: false,
            qrCodeUrl: "",
            paySucc: false,
            showDureCard: false,
            durgList:[],
            totalOpenDrug: 0,//总条数
            pageSizeOpenDrug: 5,//每页5条
            currentPageOpenDrug: 1,//
            drugOpenName: "",
            showOpenDrug: true,
            dialogOpenDrugVisible: false,
            statusa: 0,
            newOpenDrug:{
               drugName: "",
               number: ""
            },
            recipeId: "",
            editModalOpenDrugVisible: false,
            editedOpenDrug:{},
            outTradeNo:"",
            editOpenDrugRules: {
                number: [
                    {required: true, message: '请输入数量', trigger: 'blur'},
                    {pattern: /^[1-9]\d*$/, message: "请填入正确的药品数量", trigger: 'blur'}
                ],
            },
            resetOpenDrugForm(){//重置排班信息
                v.newOpenDrug = {
                    drugName: "",
                    number: ""
                };
            },
            newOpenDrugRules:{
                drugName: [
                    {required: true, message: '请输入药品名称', trigger: 'blur'},
                ],
                number: [
                    {required: true, message: '请输入药品数量', trigger: 'blur'},
                ],
            },
            /*==========================处方信息模块return结束===========================================*/
            showEdit:false,
            newPassword: '',
            confirmNewPassword: '',
            newEmail: '',

            uploadUrl:'/pa/doctor/api/uploads/' ,// 设置上传头像的后端接口地址
            headers:{},
            token:"",
            passwordMismatch: false, // 密码是否不一致的标志位
            verificationCode: '', // 用于存储生成的验证码
            enteredCode: '', // 用于存储用户输入的验证码


            from:{
                newPhone:'',
                username:localStorage.getItem('currentUserName')
            }

        }
    },
    //初始化加载后钩子函数
    mounted(){
        this.token=localStorage.getItem('localJwt')
        this.headers={token:this.token}
        this.checkToken();

    },
    computed: {
        switchValue() {
            const switchObj = {};
            this.tableDoctorData.forEach((doctor) => {
                switchObj[doctor.id] = doctor.status === 0;
            });
            return switchObj;
        },
        switchUserValue(){
            const switchUserObj = {};
            this.tableUserData.forEach((user) => {
                switchUserObj[user.id] = user.status === 0;
            });
            return switchUserObj;
        },
    },
    methods:{

        //判断用户是否有token
        checkToken(){
            console.log(0)
            if(localStorage.getItem("localJwt")===null){
                console.log("1")
                location.href="/login.html"
            }
        },


        handleCommandAV(command) {
            if (command == 'openEditInfoDialog') {
                this.openEditInfoDialog();
            }  else if (command == 'openLogoutConfirm') {
                this.openLogoutConfirm();
            }
        },
        openEditInfoDialog() {
            console.log('准备弹出修改当前用户资料的对话框');
            v.showEdit = true;

        },
        closeEditInfoDialog() {
            this.showEdit = false;
        },
        performUpdater() {
            console.log(typeof this.enteredCode, this.enteredCode);
            console.log(typeof this.verificationCode, this.verificationCode);

            if (this.enteredCode === this.verificationCode) {
                console.log(this.enteredCode)

            }else {
                this.$message.error('验证码错误，请重新输入。');
                return; // 停止继续执行
            }



            // 验证新密码和再次输入的密码是否相等

            if (this.newPassword !== this.confirmNewPassword) {
                this.$message.error('两次输入的密码不一致，请重新输入。');
                this.passwordMismatch = true; // 设置密码不一致的
                return; // 停止继续执行
            }else {
                this.passwordMismatch = false; // 重置为false，去掉错误状态
            }

            // 验证新密码是否为6位的字母和数字组合
            const passwordPattern = /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{6})$/;
            if (!passwordPattern.test(this.newPassword)) {
                if (this.newPassword !== "") {
                    this.$message.error('密码必须是6位的字母和数字组合。');
                    return; // 停止继续执行
                }


            }



            const formData = new FormData();


            formData.append('newPassword', this.newPassword);
            formData.append('newPhone', v.from.newPhone);
            formData.append('newEmail', this.newEmail);
            formData.append('currentUserAvatar',this.currentUserAvatar);
            const localJwt = localStorage.getItem('localJwt');

            // 使用 Axios 发送请求
            axios.post('/pa/doctor/updateEdit',formData, {
                headers: {
                    'token': localStorage.getItem('localJwt'),

                }
            })
                .then(response => {
                    // 处理后端的响应
                    console.log(response.data);
                    if(response.data.code===2001){
                        console.log("修改成功")
                        localStorage.setItem('currentUserAvatar',response.data.data.Avatar) //刷新头像信息


                    }

                    this.closeEditInfoDialog(); // 成功后关闭对话框
                })
                .catch(error => {
                    console.error('错误:', error);
                });



            this.closeEditInfoDialog();
            this.handleAvatarSuccess();

        },

        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJPG) {
                this.$message.error('只允许上传 JPG/PNG 格式的图片');
            }
            return isJPG;
        },
        handleAvatarSuccess(res, file) {

            this.currentUserAvatar = URL.createObjectURL(file.raw);


        },
        generateVerificationCode() {
            axios.post("/pa/sends/changeyz",v.from).then(function (response) {


                if (response.data.code==2006) {

                    v.$message.success("发送成功");
                    console.log(response.data.data.code)

                    v.verificationCode=response.data.data.code



                }else {
                    v.$message.error("发送失败");
                }



            });
        },


        openLogoutConfirm() {
            let message = '您确定退出登录吗？';
            this.$confirm(message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                localStorage.removeItem('localJwt');
                localStorage.removeItem('currentUserName');
                localStorage.removeItem('currentUserAvatar');

                axios.get("/pa/users/logout").then(function () {
                    location.href='/index.html'//页面数据
                })


            }).catch(() => {
            });
        },
        loadCurrentUserInfo() {

            this.currentUserName = localStorage.getItem('currentUserName');
            this.currentUserAvatar = localStorage.getItem('currentUserAvatar');

        },
        handleSelectionChange1(val) {
            this.multipleSelection = val;
        },
        handleMenuDoctorSelect(index) {
            this.selectedDoctorIndex = index;
            if(index==='2'){ /*点击医生信息模块，会传过来相对应的index的值*/
                this.showDoctorInfo();/*showDoctorInfo，跳转到这个方法，发送请求给后端查询数据，渲染页面上*/
            }
            if(index==='3'){
                v.showEmpty = true;
                v.showSource = false;
                v.showAppointCard = false;
                v.showDoctorCard = false;
                v.showSourceCard = false;
                this.currentDoctorId = -1;
                this.currentAppointId = -1;

                this.showDeptInfo();/*showDeptInfo，跳转到这个方法，发送请求给后端查询数据，渲染页面上*/
            }
            if(index==='4'){ /*点击药品信息模块，会传过来相对应的index的值*/
                this.showDrugInfo();/*showDrugInfo，跳转到这个方法，发送请求给后端查询数据，渲染页面上*/
            }
            if(index==='5'){ /*点击预约管理模块，会传过来相对应的index的值*/
                this.showBookingInfo();/*showBookingInfo，跳转到这个方法，发送请求给后端查询数据，渲染页面上*/
            }
            if(index==='6'){ /*点击就诊记录模块，会传过来相对应的index的值*/
                this.showRecordInfo();/*自定义showRecordInfo，跳转到这个方法，发送请求给后端查询数据，渲染页面上*/
            }
            if(index==='7'){
                this.showRecipeInfo();
                v.showRecipeCard=true;
                v.showOpenDrug = true
                v.showDureCard = false;
            }
        },


        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.clearSelection();
            }
        },
        clearSelection() {
            this.$refs.multipleTable.clearSelection();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },



        /*===============================医生模块方法开始====================================*/

        handleSwitchChange(id){
            axios.put("/pa/doctor/changStatus/"+id,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }}).then(function (response) {
                console.log(response.data.data.status+"===")
                if(response.data.code==1){
                    if(response.data.data.status==1){
                        v.$message.error("禁用")
                        this.showDoctorInfo();
                    }else {
                        v.$message.success("启用")
                        this.showDoctorInfo();
                    }
                }
            }.bind(this))
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            v.pageSize = val; // 每次修改每页条数时，重置当前页数为第一页
            this.showDoctorInfo();
        },
        handleCurrentChange(page) {
            console.log("进来了jahhah")
            this.currentPage = page;
            this.showDoctorInfo();
        },
        showDoctorInfo() {//所有医生的基本信息
            console.log("哈哈啊啊哈哈")
            axios.get("/pa/doctor/selectAll?page=" + v.currentPage + "&pageSize=" + v.pageSize+"&no="+v.searchNo+"&nickName="+v.searchName,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }}).then(function (response) {
                if(response.data.code==1){
                    console.log(response.data.data.doctors+"===")
                    v.tableDoctorData = response.data.data.doctors;
                    v.total = response.data.data.total;
                }else {
                    v.$message.error("数据为空");
                }
            })
        },
        searchDoctors(){
            this.currentPage = 1;
            this.showDoctorInfo();
        },

        getDoctorById(id) {
            // 假设tableDoctorData是医生数据的数组
            return this.tableDoctorData.find(doctor => doctor.id === id);
        },


        resetForm() {
            this.$refs.editForm.resetFields();
        },



        /*===============================医生模块方法结束====================================*/


        /*==================================科室信息模块方法开始===================================*/
        showDeptInfo(){/*所有科室的信息*/
            v.showDeptCard = true
            console.log("就是这里")
            axios.get("/pa/dept/selectChild?page="+v.currentPageDept+"&pageSize="+v.pageSizeDept+"&deptname="+v.searchDeptName,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }}).then(response=>{
                if(response.data.code===1){
                    console.log(response.data.data)
                    v.tableDeptData = response.data.data.depts;
                    v.totalDept = response.data.data.total;
                }
            })
        },
        searchDepts(){
            this.currentPageDept = 1;
            this.showDeptInfo();
        },
        findDoctors(){
            this.currentPageDeptAndDoctor = 1;
            this.selectDeptByIdFindDoctor1(v.deptId);
        },
        handleSizeChangeDept(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeDept = val; // 每次修改每页条数时，重置当前页数为第一页
            this.showDeptInfo();
        },
        handleCurrentChangeDept(page) {
            console.log("进来了jahhah")
            this.currentPageDept = page;
            this.showDeptInfo();
        },
        handleSizeChangeDeptAndDoctor(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeDeptAndDoctor = val; // 每次修改每页条数时，重置当前页数为第一页
            this.selectDeptByIdFindDoctor();
        },
        handleCurrentChangeAndDoctor(page) {
            console.log("进来了jahhah")
            this.currentPageDeptAndDoctor = page;
            this.selectDeptByIdFindDoctor();
        },


        handleSizeChangeDoctorAppoint(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeDeptAndDoctorAppoint = val; // 每次修改每页条数时，重置当前页数为第一页
            this.showSchedules(v.doctor);
        },
        handleCurrentChangeDoctorAppoint(page) {
            console.log("进来了jahhah")
            this.currentPageDeptAndDoctorAppoint = page;
            this.showSchedules(v.doctor);
        },


        resetDeptForm(){//重置科室信息
            v.newDept = {
                deptremark: '',
            };
        },
        resetAppointForm(){//重置排班信息
            v.newAppoint = {
                schedulTime: '',
                sourceTotal: '',
                sourceSurplus: '',
            };
        },
        resetSourceForm(){//重置排班时间段信息
            v.newSource = {
                frameTime: '',
                endTime: '',
                sourceSurplus: '',
                sourceTotal: ''
            };
        },
        submitAppointEdit(){
            this.$refs.editAppointForm.validate((valid) => {
                if(v.editedAppoint.sourceTotal<v.editedAppoint.sourceSurplus){
                    v.$message.error("剩余号源不能大于号源总量")
                    return;
                }
                if(valid){
                    const updateAppoint = {
                        id:this.editedAppoint.id,
                        schedulTime:this.editedAppoint.schedulTime,
                        sourceTotal:this.editedAppoint.sourceTotal,
                        sourceSurplus:this.editedAppoint.sourceSurplus
                    }
                    v.editedAppoint = updateAppoint;
                    axios.put("/pa/appoint/updateById",v.editedAppoint,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                            // 'Content-Type': 'application/json'
                        }}).then(response=>{
                        if(response.data.code===1){
                            v.tableAppointData = response.data.data;
                            v.$message.success("更新成功");
                            this.editModalAppointVisible = false;
                            this.showSchedules(v.doctor);
                        }else if(response.data.code===2002){
                            v.$message.success("操作失败");
                        }
                    }).catch(error =>{
                        console.error('排班数据更新失败',error)
                    })
                }
            })
        },
        submitDeptEdit(){
            this.$refs.editDeptForm.validate((valid) => {
                if(valid){
                    const updateDept = {
                        id:this.editedDept.id,
                        deptremark:this.editedDept.deptremark
                    }
                    console.log("id:"+this.editedDept.id)
                    v.editedDept = updateDept;
                    axios.put("/pa/dept/updateById",v.editedDept,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                            // 'Content-Type': 'application/json'
                        }}).then(response=>{
                        if(response.data.code===1){
                            v.tableDeptData = response.data.data;
                            v.$message.success("更新成功");
                            this.editModalDeptVisible = false;
                            this.showDeptInfo();
                        }else if(response.data.code===2002){
                            v.$message.success("操作失败");
                        }
                    }).catch(error =>{
                        console.error('公告数据更新失败',error)
                    })
                }
            })
        },


        getDeptById(id){
            // tableNoticeData是公告数据的数组
            console.log("数据:"+this.tableDeptData.find(dept => dept.id === id))
            return this.tableDeptData.find(dept => dept.id === id);
        },
        /*根据id获取每个科室有多少医生*/
        selectDeptByIdFindDoctor(deptId){
            v.showEmpty = false;
            v.deptId = deptId;
            if (this.currentDoctorId === deptId) {
                console.log("医生来")
                // 点击已显示的按钮，隐藏卡片
                this.currentDoctorId = -1; // 更新为不存在的科室ID
                this.showDoctorCard = false;
                v.showEmpty = true;
            } else {
                console.log("医生否则来")
                setTimeout(() => {
                    v.loading = false; // 一秒后停止加载状态
                }, 1000);
                v.loading = true;
                axios.get("/pa/dept/selectByDeptId?page="+v.currentPageDeptAndDoctor+"&pageSize="+v.pageSizeDeptAndDoctor+"&deptId="+deptId+"&no="+v.no+"&nickName="+v.nickName,{
                    headers: {
                        'token': localStorage.getItem('localJwt'),
                        // 'Content-Type': 'application/json'
                    }}).then(response=>{
                    if(response.data.code===1){
                        console.log("条数:"+response.data.data.total)
                        v.ListDoctor = response.data.data.doctorList;
                        v.totalDeptAndDoctor =  response.data.data.total
                        v.currentDoctorId = deptId; // 更新当前科室ID
                    }
                })
                this.showDoctorCard = true;

            }
        },

        selectDeptByIdFindDoctor1(deptId){
            axios.get("/pa/dept/selectByDeptId?page="+v.currentPageDeptAndDoctor+"&pageSize="+v.pageSizeDeptAndDoctor+"&deptId="+deptId+"&no="+v.no+"&nickName="+v.nickName,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }}).then(response=>{
                if(response.data.code===1){
                    console.log("条数:"+response.data.data.total)
                    v.ListDoctor = response.data.data.doctorList;
                    v.totalDeptAndDoctor =  response.data.data.total
                }
            })
        },

        showSchedules(doctor){//点击号源显示这个医生的日排班信息
            v.showDeptCard = false;
            v.showDoctorCard = false;
            v.showAppointCard = true;
            v.showSource = true;
            v.showSourceCard =false;
            if(doctor.nickName!=null){
                v.currentDoctorName = doctor.nickName;
                v.currentDoctorNo = doctor.no;
            }
            if(v.searchDeptAppointDate!=null && v.searchDeptAppointDate!=''){
                console.log("过来了====="+doctor.nickName,":"+doctor.no);
                var formattedTime = v.searchDeptAppointDate.toLocaleString();
                v.searchDeptAppointDate = formattedTime;
                console.log( v.searchDeptAppointDate );
            }
            console.log("===="+v.currentDoctorNo);
            axios.get("/pa/dept/selectAppoint?page="+v.currentPageDeptAndDoctorAppoint+"&pageSize="+v.pageSizeDeptAndDoctorAppoint+"&no="+v.currentDoctorNo+"&schedulTime="+v.searchDeptAppointDate,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }}).then(response=>{
                v.tableAppointData = response.data.data.deptAppoint;
                v.totalDeptAndDoctorAppoint = response.data.data.total;
                v.searchDeptAppointDate = '';
                /*this.selectAppoint(v.newSource.appointId);*/
            })
        },
        goBack(){//点击返回图标
            v.showAppointCard = false;
            v.showDeptCard = true;
            v.showDoctorCard = true;
            v.showSource = false;
            v.showSourceCard =false;
        },
        //根据id删除日排班
        deleteAppointById(id){
            console.log("进来了哦")
            axios.delete("/pa/appoint/deleteById/"+id,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }}).then(response=>{
                if(response.data.code===1){
                    v.$message.success("删除成功");
                    v.showSchedules(v.doctor);
                }
            })
        },
        getAppointById(id){
            console.log("数据:"+this.tableAppointData.find(appoint => appoint.id === id))
            return this.tableAppointData.find(appoint => appoint.id === id);
        },
        //根据id编辑日排班
        editedAppointById(id){
            const appoint = this.getAppointById(id);
            if(appoint){
                this.editedAppoint = {...appoint};
                this.editModalAppointVisible = true;
            }
        },
        updateSelection(){
            // 获取选中的医生信息的ID
            const selectedIds = this.multipleSelection.map((appoint) => appoint.id);
            if (selectedIds.length === 0) {
                this.$message.warning('请先选择要发布的医生排班');
                return;
            }
            v.ids = selectedIds;
            // 弹出确认删除的对话框
            this.$confirm('确认发布吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(()=>{
                axios.put("/pa/appoint/updateByIds",{ data: v.ids },{
                    headers: {
                        'token': localStorage.getItem('localJwt'),
                        // 'Content-Type': 'application/json'
                    }}).then(response=> {//因为要重新加载医生信息，所以要回调，用=》
                    if(response.data.code===1){
                        v.$message.success("发布成功");
                        /* v.showSourceCard =false;*/
                        v.showSchedules(v.doctor);//重新加载信息
                    }else {
                        v.$message.error("发布失败");
                    }
                })
            }) .catch(() => {
                // 用户点击取消，不执行任何操作
            });
        },
        showAddSource(){
            this.newSource = {
                frameTime: '',
                endTime: '',
                sourceSurplus: '',
                sourceTotal: ''
            };
            this.dialogSourceVisible = true; // 将模态框的可见性设置为true
        },
        showAddAppoint(){
            this.newAppoint = {
                schedulTime: '',
                sourceTotal: '',
                sourceSurplus: '',
            };
            this.dialogAppointVisible = true; // 将模态框的可见性设置为true
        },
        /*关闭模态框，把数据都清空*/
        resetNewAppoint() {
            v.newAppoint = {
                schedulTime: '',
                sourceTotal: '',
                sourceSurplus: '',
            };
            v.$refs.newAppointForm.resetFields();
        },
        addSource(){
            this.$refs.newSourceForm.validate((valid) => {
                if (valid) {
                    const frameTime = v.newSource.frameTime
                    const endTime = v.newSource.endTime
                    const sourceTotal = v.newSource.sourceTotal
                    const sumSourceTotal = parseInt(sourceTotal)+v.sourceTotal;//原有的时间段排班累加的和输入框添加的只和
                    console.log("输入框输入的:"+sourceTotal)
                    console.log("累加的："+v.sourceTotal)
                    console.log("累加sum的："+sumSourceTotal)
                    console.log("不是输入的:"+v.appointTotal)
                    const sourceSurplus = v.newSource.sourceSurplus
                    if(sumSourceTotal>v.appointTotal){
                        v.$message.error('添加的时间段号源总量超过了当天的号源总量')
                        return;
                    }
                    if(v.sourceTotal==v.appointTotal){
                        v.$message.error('当天的号源总量已全部排完,不能再添加')
                        return;
                    }
                    if(frameTime==='' || endTime===''){
                        v.$message.error('起始时间和结束时间不能为空')
                        return;
                    }else if(frameTime && endTime && frameTime >= endTime){
                        v.$message.error('起始时间必须早于结束时间')
                        return;
                    }else if(sourceTotal>v.appointTotal){
                        v.$message.error('号源总量不能超过'+v.appointTotal+"个")
                        return;
                    }/*else if(sourceSurplus>v.sourceSurplus){
                        v.$message.error('剩余号源不能大超过'+v.sourceSurplus+"个")
                        return;
                    }*/else if(sourceTotal<sourceSurplus){
                        v.$message.error('剩余号源不能超过号源总量')
                        return;
                    }else if(sourceTotal==v.sourceTotal){
                        v.$message.error('当天的号源总量已全部排完,不能再添加')
                        return;
                    }
                    console.log(v.AppointId);
                    v.newSource.appointId = v.AppointId;
                    console.log("AppointId:"+v.newSource.appointId)
                    axios.post("/pa/source/addSource",v.newSource,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                            // 'Content-Type': 'application/json'
                        }}).then(response=>{
                        if(response.data.code==1){
                            v.$message.success("添加成功");
                            v.dialogSourceVisible = false;
                            /*this.selectAppointByIdFindSource(v.newSource.appointId);*/
                            this.selectAppoint(v.newSource.appointId);
                        }
                    })
                }
            });
        },
        selectAppoint(appointId){
            axios.get("/pa/source/selectAppoint?id="+appointId,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }}).then(response=>{
                if(response.data.code==1){
                    v.ListSource = response.data.data;
                }
            })
        },
        addAppoint(){
            this.$refs.newAppointForm.validate((valid) => {
                if (valid) {
                    if(v.newAppoint.sourceTotal<v.newAppoint.sourceSurplus){
                        v.$message.error("剩余号源不能大于号源总量")
                        return;
                    }
                    v.newAppoint.doctorNo = v.currentDoctorNo;
                    // 执行提交逻辑
                    axios.post("/pa/appoint/addAppoint",v.newAppoint,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                            // 'Content-Type': 'application/json'
                        }}).then(function (response) {
                        if(response.data.code===1){
                            v.$message.success("添加成功");
                            v.resetNewAppoint();
                            v.dialogAppointVisible = false;
                            v.showSchedules(v.doctor);
                        }else if(response.data.code===4002){
                            v.$message.error(response.data.msg);
                        }
                    })
                }
            });
        },
        //点击日排班号源，根据id渲染时间段数据
        selectAppointByIdFindSource(AppointId){
            v.showSource = false;
            v.AppointId = AppointId;
            if (this.currentAppointId === AppointId) {
                // 点击已显示的按钮，隐藏卡片
                this.showSourceCard = false;
                this.currentAppointId = -1; // 更新为不存在的科室ID
                v.showSource = true;
            } else {
                console.log("否则来")
                setTimeout(() => {
                    v.loadingSource = false; // 一秒后停止加载状态
                }, 1000);
                v.loadingSource = true;
                axios.get("/pa/source/selectByAppointId?id="+AppointId,{
                    headers: {
                        'token': localStorage.getItem('localJwt'),
                        // 'Content-Type': 'application/json'
                    }}).then(response=>{
                    if(response.data.code===1){
                        v.ListSource = response.data.data;
                        v.currentAppointId = AppointId; // 更新当前科室ID
                        v.AppointSurplus = response.data.data.appointSurplus;
                        v.AppointTotal = response.data.data.appointTotal;
                        console.log(response.data.data.appointSurplus+"==="+response.data.appointSurplus)
                        console.log(response.data.data); // 输出整个对象

                        let sourceTotal = 0; // 累加变量
                        let sourceSurplus = 0; // 累加变量
                        // 循环遍历数据并取出某一个数据
                        response.data.data.forEach(item => {
                            const appointTotal = item.appointTotal;
                            const appointSurplus = item.appointSurplus;
                            v.appointTotal = appointTotal;
                            v.appointSurplus = appointSurplus;
                            sourceTotal += item.sourceTotal; // 累加 sourceTotal
                            sourceSurplus += item.sourceSurplus; // 累加 sourceSurplus
                        });
                        v.sourceTotal = sourceTotal; // 将累加结果赋值给 sourceTotal
                        v.sourceSurplus = sourceSurplus; // 将累加结果赋值给 sourceSurplus
                        console.log("当天排班的号源总量:"+ v.appointTotal)
                        console.log("每个时间段累加的总号源:"+ v.sourceTotal)
                    }
                })
                this.showSourceCard = true;
            }
        },
        /*==================================科室信息模块方法结束===================================*/



        /*==================================药品息模块方法结束===================================*/

        showDrugInfo() {
            //所有预约的基本信息
            const DrugLike={
                page:v.currentPageDrug,
                pageSize:v.pageSizeDrug,
                drugName:v.drugName,
                drugNo:v.drugNo,
            }
            axios.post("/pa/drug/selectAll",DrugLike,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }
            }).then(function (response) {
                if(response.data.code==1){
                    v.tableDrugData = response.data.data.drugs;
                    v.totalDrug = response.data.data.total;

                }else {
                    v.$message.error("数据为空");
                }
            })
        },
        handleSizeChangeDrug(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeDrug = val; // 每次修改每页条数时，重置当前页数为第一页
            this.showDrugInfo();
        },
        handleCurrentChangeDrug(page) {
            console.log("进来了")
            this.currentPageDrug = page;
            this.showDrugInfo();
        },

        searchDrug(){
            this.currentPageDrug = 1;
            this.showDrugInfo();
        },



        /*==================================药品信息模块方法结束===================================*/




        /*==================================预约管理模块方法开始======================================*/
        showBookingInfo() {
            //所有预约的基本信息
            const bookingLike={
                page:v.currentPageBooking,
                pageSize:v.pageSizeBooking,
                nickname:v.nickName,//预约人
                bookDoctorName:v.bookDoctorName,//医生名称
                doctorNo:localStorage.getItem('no')
            }
            axios.post("/pa/booking/getDoctorSelectAll",bookingLike,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }
            }).then(function (response) {
                if(response.data.code==1){
                    v.tableBookingData = response.data.data.booking;
                    v.totalBooking = response.data.data.total;

                }else {
                    v.$message.error("数据为空");
                }
            })
        },
        handleSizeChangeBooking(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeBooking = val; // 每次修改每页条数时，重置当前页数为第一页
            this.showBookingInfo();
        },
        handleCurrentChangeBooking(page) {
            console.log("进来了jahhah")
            this.currentPageBooking = page;
            this.showBookingInfo();
        },
        cancelBooking(id){
            axios.put("/pa/booking/updateByIdStatus/"+id,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }
            }).then(function (response) {
                if(response.data.code==1){
                    v.$message.success("取消成功")
                    v.showBookingInfo();
                }else if(response.data.code==4003){
                    v.$message.success(response.data.msg)
                }else {
                    v.$message.success(response.data.msg)
                }
            })
        },
        deleteBookingSelection(){
            // 获取选中的用户信息的ID
            const selectedIds = this.multipleSelection.map((booking) => booking.id);
            if (selectedIds.length === 0) {
                this.$message.warning('请先选择要删除的预约信息');
                return;
            }
            console.log("ids="+selectedIds)
            v.bookingIds = selectedIds;
            let data = v.bookingIds
            const currentPageBooking = v.currentPageBooking; // 保存当前页码
            // 弹出确认删除的对话框
            this.$confirm('确认删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(()=>{
                axios.post("/pa/booking/deleteByIds",data,{
                    headers: {
                        'token': localStorage.getItem('localJwt')
                        // 'Content-Type': 'application/json'
                    }
                }).then(response=> {//因为要重新加载预约信息，所以要回调，用=》
                    if(response.data.code===1){
                        v.$message.success("删除成功");
                        if (v.tableBookingData.length === 1 && currentPageBooking > 1) {
                            // 如果删除前是最后一页且只有一条数据，则返回上一页
                            v.currentPageBooking = currentPageBooking - 1;
                            v.showBookingInfo();//重新加载信息
                        }else {
                            v.showBookingInfo();//重新加载信息
                        }
                    }else {
                        v.$message.error("删除失败");
                    }
                })
            }) .catch(() => {
                // 用户点击取消，不执行任何操作
            });
        },
        searchDoctorBooking(){
            this.currentPageBooking = 1;
            this.showBookingInfo();
        },
        speak(action, id,dept) {//语音播报
            if ('speechSynthesis' in window) {
                const speechSynthesis = window.speechSynthesis;
                const speechText = new SpeechSynthesisUtterance(`请 ${id} 号患者到${dept} ${action}`);
                speechSynthesis.speak(speechText);
                axios.get("/pa/booking/updateById/"+id,{
                    headers: {
                        'token': localStorage.getItem('localJwt'),
                        // 'Content-Type': 'application/json'
                    }
                }).then(response=>{
                    if(response.data.code==1){
                        this.showBookingInfo();
                    }
                })
            } else {
                console.log('浏览器不支持语音合成');
            }
        },
        /*关闭模态框，把数据都清空*/
        resetNewBooking() {
            v.newBooking = {
                schedulTime: '',
                healthStatus: '',
            };
            v.$refs.newBookingForm.resetFields();
        },
        resetBookingForm(){//重置症状信息
            v.newBooking = {
                schedulTime: '',
                healthStatus: '',
            };
        },
        addRecord() {
            this.$refs.newBookingForm.validate((valid) => {
                if (valid) {
                    // 执行提交逻辑
                    axios.post("/pa/booking/addRecord",v.newBooking,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                            // 'Content-Type': 'application/json'
                        }
                    }).then(function (response) {
                        if(response.data.code===1){
                            v.$message.success("添加成功");
                            v.dialogNoticeVisible = false;
                            v.showBookingInfo();
                        }
                    })
                }
            });
        },
        handleComplete(id){
            const booking = this.getBookingById(id);
            if(booking){
                this.editedBooking = {...booking};
                if(this.editedBooking.appointmentStatus===4){
                    v.$message.error("该患者已就诊完成")
                    return;
                }else if(this.editedBooking.appointmentStatus===1){
                    v.$message.error("该患者预约成功，等待叫号")
                    return;
                }else if(this.editedBooking.appointmentStatus===3){
                    v.$message.error("该患者已取消")
                    return;
                }
                this.editModalBookingVisible = true;
            }
        },
        getBookingById(id){
            return this.tableBookingData.find(booking => booking.id === id);
        },
        submitBookingEdit(){
            this.$refs.editBookingForm.validate((valid) => {
                if(valid) {
                    const updateBooking = {
                        id:this.editedBooking.id,
                        schedulTime:this.editedBooking.schedulTime,
                        nickName:this.editedBooking.nickName,
                        deptName:this.editedBooking.deptName,
                        doctorNo:this.editedBooking.doctorNo,
                        doctorName:this.editedBooking.name,
                        healthStatus:this.editedBooking.healthStatus
                    }
                    v.editedBooking = updateBooking;
                    axios.post("/pa/booking/addRecord",v.editedBooking,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                            // 'Content-Type': 'application/json'
                        }
                    }).then(response=>{
                        if(response.data.code===1){
                            v.$message.success("完成");
                            this.editModalBookingVisible = false;
                            this.showBookingInfo();
                        }
                    }).catch(error =>{
                        console.error('预约数据更新失败',error)
                    })
                }
        })
        },
        /*==================================预约管理模块方法结束======================================*/
        searchDoctorRecord(){
            this.currentPageRecord = 1;
            this.showRecordInfo();
        },
        showRecordInfo(){
            console.log("v.RnickName="+v.RnickName)
            //当前医生的患者的基本信息
            const bookingLike={
                page:v.currentPageRecord,
                pageSize:v.pageSizeRecord,
                nickName:v.RnickName,//预约人
               /*直接获取当前登录医生的工号*/
                doctorNo: localStorage.getItem('no')
            }
            axios.post("/pa/recipe/selectAll",bookingLike,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }
            }).then(function (response) {
                if(response.data.code==1){
                    v.tableRecordData = response.data.data.record;
                    v.totalRecord = response.data.data.total;
                }else {
                    v.$message.error("数据为空");
                }
            })
        },
        handleSizeChangeRecord(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeRecord = val; // 每次修改每页条数时，重置当前页数为第一页
            this.showRecordInfo();
        },
        handleCurrentChangeRecord(page) {
            console.log("进来了jahhah")
            this.currentPageRecord = page;
            this.showRecordInfo();
        },
        deleteRecord(id){
            console.log("进来了")
            const currentPageRecord = v.currentPageRecord; // 保存当前页码
            axios.delete("/pa/recipe/deleteById/"+id,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                    // 'Content-Type': 'application/json'
                }
            }).then(response=>{
                if(response.data.code===1){
                    if (v.tableRecordData.length === 1 && currentPageRecord > 1) {
                        // 如果删除前是最后一页且只有一条数据，则返回上一页
                        v.currentPageRecord = currentPageRecord - 1;
                        v.showRecordInfo();//重新加载信息
                    }else {
                        v.showRecordInfo();//重新加载信息
                    }

                    v.$message.success("删除成功")
                    v.showRecordInfo();
                }else {
                    v.$message.error("删除失败")
                }
            });
        },
/*=====================================就诊记录方法结束============================================*/
/*=====================================处方信息方法开始============================================*/
        showRecipeInfo(){
            const recipeLike={
                page:v.currentPageRecipe,
                pageSize:v.pageSizeRecipe,
                nickName:v.nickName,//预约人
                /*直接获取当前登录医生的工号*/
                doctorNo: localStorage.getItem("no")
            }
            console.log(recipeLike.doctorNo+"doctorNo")
            axios.post("/pa/recipe/selectRecipeAll",recipeLike,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                }
            }).then(function (response) {
                if(response.data.code==1){
                    //v.tableRecipeData = response.data.data.recipe;
                    v.totalRecipe = response.data.data.total;
                    v.tableRecipeData = response.data.data.recipe.map((item) => ({
                        ...item,
                        disabled: false,
                    }));
                }else {
                    v.$message.error("数据为空");
                }
            })
        },
        handlePayment(){//打印按钮
            //清空之前的二维码
            const qrcodeContainer = document.getElementById("qrcode");
            if (qrcodeContainer !== null) {
                qrcodeContainer.innerHTML = ""; // 清空容器数据
            }
            // 获取选中的用户信息的ID
            const selectedIds = this.multipleSelection.map((recipe) => recipe.id);
            console.log("进来了"+selectedIds)
            if (selectedIds.length === 0) {
                this.$message.warning('请先选择要缴费的用户');
                return;
            }
            if (selectedIds.length >1) {
                this.$message.error('请先选择一个用户进行缴费');
                return;
            }
            v.RecipeIds = selectedIds;//传RecipeIds
            const doctorNo =  localStorage.getItem('no')
            v.no = doctorNo
            console.log("no:"+v.no)
            axios({
                method: 'POST',
                url: "/pa/recipe/sandboxPay/"+v.RecipeIds+"/"+v.no+"/"+v.outTradeNo,
                headers: {
                    'token': localStorage.getItem('localJwt'),
                }
            }).then(res => {
                if(res.data.code===3005){
                    v.$message.error(res.data.msg)
                }else if(res.data.code===3006){
                    v.$message.error(res.data.msg)
                } else if(res.data.code===1){
                    v.$message.success("打印完成")
                    if ("WebSocket" in window) {
                        // 打开一个 web socket
                        // 通道地址按照项目进行配置
                        var ws = new WebSocket("ws://localhost:8080/bindingRecord");
                        ws.onopen = function() {
                            // Web Socket 已连接上，使用 send() 方法发送数据
                            ws.send("true");
                        };
                        ws.onmessage = function(evt) {
                            console.log("触发");
                            var received_msg = evt.data;
                            if (received_msg === 'true') {
                                // 支付成功通知
                                console.log("支付成功通知");
                                v.handlePaymentSuccess();
                            }
                           /* // 接收后台推送的数据
                            if (Boolean(evt.data)) {
                                setTimeout(() => {
                                    v.dialogVisiblePay = false;
                                    v.paySucc = false;
                                    qrcodeContainer.innerHTML = ""; // 清空容器数据
                                }, 3 * 1000);
                            }*/
                            ws.close();
                            console.log("我来了");
                        };
                        ws.onclose = function() {
                            console.log("WebSocket 连接已关闭");
                        };
                        ws.onopen = function() {
                            console.log("WebSocket 连接已打开");
                        };
                    } else {
                        // 浏览器不支持 WebSocket
                        alert("您的浏览器不支持 WebSocket!");
                    }
                }
            });
        },
        handlePaymentSuccess(){
            console.log("处理支付成功通知")
            axios.post("http://xhe96g.natappfree.cc/pa/recipe/call").then(response => {
                // 设置支付成功状态
                v.showRecipeInfo()
                console.log("完成")
            })
        },
        handleSizeChangeRecipe(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeRecipe = val; // 每次修改每页条数时，重置当前页数为第一页
            this.showRecipeInfo();
        },
        handleCurrentChangeRecipe(page) {
            console.log("进来了jahhah")
            this.currentPageRecipe = page;
            this.showRecipeInfo();
        },
        prescribe(id){//开方
            const record = this.getRecordById(id);
            if(record){
                console.log("打开")
                this.editedRecord = {...record};
                this.editModalRecordVisible = true;
            }
        },
        getRecordById(id){
            return this.tableRecordData.find(record => record.id === id);
        },
        resetRecipeForm(){//重置症状信息
            v.newRecipe = {
                schedulTime: '',
                announcements: '',
            };
        },
        submitOpenDrugEdit(){//编辑openDrug药品数量
            this.$refs.editOpenDrugForm.validate((valid) => {
                if(valid){
                    const updateOpenDrug = {
                        id:this.editedOpenDrug.id,
                        number:this.editedOpenDrug.number
                    }
                    v.editedOpenDrug = updateOpenDrug;
                    axios.post("/pa/recipe/updateByIdOpenDrug",v.editedOpenDrug,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                        }}).then(response=>{
                        if(response.data.code===1){
                            /*v.tableAppointData = response.data.data;*/
                            v.$message.success("更新成功");
                            this.editModalOpenDrugVisible = false;
                            this.queryOpenDrug(v.recipeId);
                            this.showRecipeInfo();
                        }else if(response.data.code===2002){
                            v.$message.success("操作失败");
                        }
                    })
                }
            })
        },
        submitRecordEdit(){
            this.$refs.editRecordForm.validate((valid) => {
                if(valid) {
                    const updateRecord = {
                        recordId:this.editedRecord.id,
                        schedulTime:this.editedRecord.schedulTime,
                        nickName:this.editedRecord.nickName,//患者名称
                        doctorNo:this.editedRecord.doctorNo,
                        doctorName:this.editedRecord.doctorName,//医生名称
                        announcements:this.editedRecord.announcements
                    }
                    console.log("id="+updateRecord.bookingId,"schedulTime="+updateRecord.schedulTime,"nickName="+updateRecord.nickName)
                    console.log("doctor="+updateRecord.doctorNo,"announcements="+updateRecord.announcements+"doctorName="+updateRecord.doctorName)
                    v.editedRecord = updateRecord;
                    axios.post("/pa/recipe/addRecipe",v.editedRecord,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                            //'Content-Type': 'application/json'
                        }
                    }).then(response=>{
                        if(response.data.code===1){
                            v.$message.success("完成");
                            this.editModalRecordVisible = false;
                            this.showRecordInfo();
                        }
                    }).catch(error =>{
                        console.error('添加失败',error)
                    })
                }
            })
        },
        kAddDrug(){//给患者开药
            this.newOpenDrug = {
                drugName: "",
                number: "",
                recipeId: v.recipeId
            };
            this.dialogOpenDrugVisible = true; // 将模态框的可见性设置为true
        },
        addOpenDrug(){ //点击开药，模态框里面的提交按钮功能
            this.$refs.OpenDrugForm.validate((valid) => {
                if (valid) {
                    console.log(JSON.stringify(v.newOpenDrug))
                    axios.post("/pa/recipe/addOpenDrug",v.newOpenDrug,{
                        headers: {
                            'token': localStorage.getItem('localJwt'),
                        }
                    }).then(response=>{
                        if(response.data.code===1){
                            v.outTradeNo = response.data.data;//订单的订单号
                            this.dialogOpenDrugVisible = false;
                            this.queryOpenDrug(v.recipeId);
                            this.showRecipeInfo();
                        }
                    })
                }
            });
        },
        /*关闭模态框，把数据都清空*/
        resetNewOpenDrug() {
            v.newOpenDrug = {
               drugName: "",
               number: ""
            };
            v.$refs.OpenDrugForm.resetFields();
        },
        queryDrug(){//根据药品名称查询药品

        },
        deleteDrug(id){//删除开好药的药品，重新开药的作用
            axios.delete("/pa/recipe/deleteByIdOpenDrug/"+id,{
                headers: {
                    'token': localStorage.getItem('localJwt'),
                }
            }).then(response=>{
                if(response.data.code===1){
                    v.$message.success("删除成功");
                    this.queryOpenDrug(v.recipeId);
                    this.showRecipeInfo();
                }
            })
        },
        queryOpenDrug(id){//点击配药查询该患者的配药情况
            v.recipeId = id
            console.log("进来看"+id)
            v.showOpenDrug = false
            v.showDureCard = true;
            axios.get("/pa/recipe/selectOpenDrug?page="+v.currentPageOpenDrug+"&pageSize="+v.pageSizeOpenDrug+"&id="+id,{
                    headers: {
                        'token': localStorage.getItem('localJwt'),
                    }
                }).then(response=>{
                if(response.data.code===1){
                    console.log(response.data.data.openDrugs)
                    v.statusa = response.data.data.status;
                    v.durgList = response.data.data.openDrugs;
                    v.totalOpenDrug = response.data.data.total;
                    console.log( v.status+" v.status")
                }
            })
        },
        getOpenDrugById(id){
            console.log("数据:"+this.durgList.find(openDrug => openDrug.id === id))
            return this.durgList.find(openDrug => openDrug.id === id);
        },
        //根据id编辑日排班
        editedOpenDrugById(id){
            const OpenDrug = this.getOpenDrugById(id);
            if(OpenDrug){
                this.editedOpenDrug = {...OpenDrug};
                this.editModalOpenDrugVisible = true;
            }
        },
        handleSizeChangeOpenDrug(val) {
            console.log(`每页 ${val} 条`);
            v.pageSizeOpenDrug = val; // 每次修改每页条数时，重置当前页数为第一页
            this.queryOpenDrug();
        },
        handleCurrentChangeOpenDrug(page) {
            console.log("进来了jahhah")
            this.currentPageOpenDrug = page;
            this.queryOpenDrug();
        },
        searchDoctorRecipe(){

        }
    }
})
